package com.heima.wemedia.service.impl;

import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.prefix}")
    private String prefix;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.校验参数
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"素材id不能为空");
        }
        //2.更新参数
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"素材信息不存在");
        }
        //3.获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if (!wmMaterial.getUserId().equals(uid)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }
        wmMaterial.setIsCollection(type);
        updateById(wmMaterial);
        //4.返回结果
        return ResponseResult.okResult();
    }

    @Transactional
    @Override
    public ResponseResult delPicture(Integer id) {
        //1.根据id查询素材数据
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材不存在");
        }
        //2.判断素材是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"素材已被引用无法删除");
        }
        //3.从数据库中删除数据
        this.removeById(id);
        //4.从oss中删除对应数据
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //1.校验参数
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        //2.执行查询
        //分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        //参数查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.lambdaQuery();
        //如果收藏字段为1。添加条件按收藏字段查询
        if (WemediaConstants.COLLECT_MATERIAL.equals(dto.getIsCollection())){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按照登录用户id查询
        queryWrapper.eq(WmMaterial::getUserId,user.getId());
        //按照创建时间降序排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageResult = this.page(page, queryWrapper);
        //3.封装结果
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), records);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.校验参数
        if(multipartFile == null || multipartFile.getSize() == 0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上传的文件不能为空");
        }
        //获取当前线程用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        //截取文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!checkFileSuffix(suffix)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        //2.上传到用户oss
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            //上传文件至oss
            String store = fileStorageService.store(prefix,filename+suffix,multipartFile.getInputStream());
            //上传成功向素材表添加数据
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(store);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);
            return ResponseResult.okResult(wmMaterial);
        }catch (IOException e){
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器异常，文件上传失败");
        }
        return null;
    }

    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     * @param suffix
     * @return
     */
    private boolean checkFileSuffix(String suffix){
        List<String> allowSuffixList = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
        for (String allowSuffix : allowSuffixList) {
            if (suffix.endsWith(allowSuffix)){
                return true;
            }
        }
        return false;
    }
}
